package com.ymx.darling.dialect.keygenerator;

import com.ymx.darling.bean.entity.id.IdType;
import com.ymx.darling.bean.sql.BoundSql;
import com.ymx.darling.bean.sql.SqlCommandType;
import com.ymx.darling.bean.sql.Statement;
import com.ymx.darling.executor.statement.StatementType;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 主键生成器
 * @author 爱Java的小于
 */
public interface KeyGenerator {
    /**
     * 执行sql前生成主键
     * @param statement sql上下文实例
     * @param entityList 实体列表
     */
    void processBefore(List<Object> entityList, Statement statement) throws SQLException;


    /**
     * 执行sql后生成主键
     * @param entityList 实例列表
     * @param statement sql上下文实例
     * @param preparedStatement 执行sql后的preparedStatement
     */
    void processAfter(List<Object> entityList, Statement statement, PreparedStatement preparedStatement) throws SQLException;


    /**
     * 创建主键生成器的Sql上下文
     *
     * @param statement statement
     * @param sql 查询主键的sql
     * @param keyType 主键类型
     * @return sequenceStatement
     */
    default Statement newGenerateKeyStatement(Statement statement, String sql, Class<?> keyType) {
        // 创建sql上下文实例
        Statement sequenceStatement = new Statement();
        sequenceStatement.setBoundSql(new BoundSql(sql));
        sequenceStatement.setStatementId(statement.getStatementId());
        sequenceStatement.setLogger(statement.getLogger());
        sequenceStatement.setStatementType(StatementType.PREPARED);
        sequenceStatement.setSqlCommandType(SqlCommandType.SELECT);
        sequenceStatement.setModule(keyType);
        sequenceStatement.setKeyGenerator(new NoneKeyGenerator());
        sequenceStatement.setNamespace(statement.getNamespace());
        sequenceStatement.setExecutor(statement.getExecutor());
        sequenceStatement.setConfiguration(statement.getConfiguration());

        return sequenceStatement;
    }


    /**
     * 获取主键生成类型
     * @return IdType
     */
    IdType getIdType();
}
